package com.vshop.service.alast.impl;

import com.alibaba.fastjson.JSON;
import com.vshop.config.dto.StringOutputConstant;
import com.vshop.entity.alast.common.ServicePlanOrderRecord;
import com.vshop.entity.callback.request.RequestResultCallback;
import com.vshop.entity.callback.response.ResponseResultCallback;
import com.vshop.entity.comentity.OrderExceptionRecord;
import com.vshop.entity.purchase.response.ResponsePurchaseService;
import com.vshop.mapper.PurchaseLogicMapper;
import com.vshop.service.agatewaytobeijing.GatewayToBeijingService;
import com.vshop.service.impl.PurchaseLogicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 辅助订购套餐的逻辑处理类
 *
 * @author lm
 * @date 2020/8/19 14:02
 */
@Component
@Slf4j
public class OrderAssistService {
    /**
     * 异步做套餐订购操作的辅助类
     */
    @Autowired
    PurchaseLogicService purchaseService;
    /**
     * 操作数据库的映射类
     */
    @Resource
    private PurchaseLogicMapper purchaseMapper;
    /**
     * 请求网关的服务类
     */
    @Autowired
    GatewayToBeijingService toBeijingService;

    /***
     * 订购方法的规范返回
     * @param retCode
     * @param resultInfo
     * @return
     */
    public String responseStr(String retCode, String resultInfo) {
        ResponsePurchaseService response = new ResponsePurchaseService();
        response.setRetCode(retCode);
        response.setResultInfo(resultInfo);
        String jsonString = JSON.toJSONString(response);
        log.info("【统一响应】：" + resultInfo + "结果：" + jsonString);
        return jsonString;
    }

    /***
     * 订购结果回调的处理结果规范返回
     * @param retCode
     * @param resultInfo
     * @return
     */
    public String responseCallbackStr(String retCode, String resultInfo) {
        ResponseResultCallback response = new ResponseResultCallback();
        response.setRetCode(retCode);
        response.setResultInfo(resultInfo);
        // 返回给调用者的报文
        String jsonString = JSON.toJSONString(response);
        log.info("【新订|续订的结果回调】响应：" + resultInfo + ";结果：" + jsonString);
        return jsonString;
    }

    /**
     * 新版本：对应表格：service_plan_order_record_t
     * <p>
     * 更新订单去订购套餐（续订或者新订）的动作，记录订购过程
     * <p>
     * 特别说明
     * <p>
     * isRequest
     * <p>
     * 未向北京订购或续订接口发出过请求-'0';向北京订购或续订接口发出过请求-'1';默认是0，请求过就要将状态变成1
     *
     * @param partnerCode
     * @param deviceCode
     * @param payId
     * @param orderNo
     * @param isRenew
     * @param isOpen
     * @return
     */
    public Integer updateOrderByOrderNo(String partnerCode, String deviceCode, String payId, String orderNo, String isRenew, String isOpen) {

        ServicePlanOrderRecord orderRecord = new ServicePlanOrderRecord();
        orderRecord.setPartnerCode(partnerCode);
        orderRecord.setDeviceCode(deviceCode);
        orderRecord.setPayId(payId);
        orderRecord.setOrderNo(orderNo);
        orderRecord.setIsRenew(isRenew);
        orderRecord.setIsOpen(isOpen);
        orderRecord.setIsRequest("1");
        return purchaseMapper.updateOrderByOrderNo(orderRecord);
    }

    /**
     * 最新版本：对应表格：service_plan_order_record_t
     * <p>
     * 新订|续订的回调之后去更新数据库记录
     * <p>
     * 根据order_status订单状态： 0-未支付； 1-未启用； 2-开始使用； 4-已取消； 3-已结束； 5-已暂停；来判定pcakageStatus激活或者未激活
     * <p>
     * order_status ！=0或者order_status ！=1  订单就算激活了
     * <p>
     * 套餐状态：1-未激活；2-已激活；
     *
     * @param callback
     * @return
     * @date 2021-01-08
     */
    public Integer updateCallback(RequestResultCallback callback) {
        Integer count;
        ServicePlanOrderRecord orderRecord = new ServicePlanOrderRecord();
        orderRecord.setOrderNo(callback.getPayId().trim());
        orderRecord.setDeviceCode(callback.getDeviceCode().trim());
        orderRecord.setIsRenew(callback.getType());
        orderRecord.setOrderResultDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        orderRecord.setOrderId(callback.getOrderId());
        orderRecord.setOrderTime(callback.getOrderDate());
        orderRecord.setOrderStartDate(callback.getActiveDate());
        orderRecord.setOrderExpireDate(callback.getExpireDate());

        if (StringOutputConstant.CODE_TWO.equals(callback.getOrderStatus())) {
            orderRecord.setPackageStatus(callback.getOrderStatus());
            count = purchaseMapper.updateCallbackOrder(orderRecord);
        } else {
            orderRecord.setPackageStatus("1");
            count = purchaseMapper.updateCallbackOrder(orderRecord);
        }
        return count;
    }

    /**
     * 根据orderNo和deviceCode查询到订单记录
     *
     * @param orderNo
     * @param deviceCode
     * @return
     */
    public ServicePlanOrderRecord queryRecord(String orderNo, String deviceCode) {

        return purchaseMapper.queryRecord(orderNo, deviceCode);
    }

    /**
     * 新版本：
     * <p>
     * 启用orderNo作为唯一订单标识之后：
     * <p>
     * 异常详情记录方法
     * <p>
     * 表名：user_order_exception_record_t
     *
     * @param partnerCode
     * @param deviceCode
     * @param payId
     * @param orderNo
     * @param exLocation
     * @param retCode
     * @param resultInfo
     */
    public void exceptionDetailsRecord(String partnerCode, String deviceCode, String payId, String orderNo, String exLocation, String retCode, String resultInfo) {

        OrderExceptionRecord record = new OrderExceptionRecord();
        record.setPartnerCode(partnerCode);
        record.setDeviceCode(deviceCode);
        record.setPayId(payId);
        record.setOrderNo(orderNo);
        record.setExcpLocation(exLocation);
        record.setRetCode(retCode);
        record.setResultInfo(resultInfo);
        purchaseMapper.storageExceptionRecord(record);
    }

    /**
     * 未避免同一个订单在遇到异常情况时发生多次没有必要的请求，只要请求到达这边，先去把数据库里面的：service_plan_order_record_t的isRequest值从0变成1，就算有异常也只去记录一次即可
     *
     * @param deviceCode
     * @param orderNo
     * @return
     */
    public Integer updateIsRequestByOrder(String deviceCode, String orderNo) {
        return purchaseMapper.updateIsRequestByOrder(deviceCode, orderNo);
    }
}